﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Serious.SweetConfig
{
	class Program
	{
		static void Main(string[] args)
		{
			try
			{
				if (args.Length == 4)
				{
					TransformConfig(args[0], args[1], args[2], args[3]);
				}
				else
				{
					Console.WriteLine("SweetConfig [Parameter Filename] [SetParameter Filename] [Source Transformation Filename] [Target Transformed Filename]");
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine("Error occurred transforming file '" + args[2] + "': " + ex.Message);
			}
		}

		private static void TransformConfig(string parameterFilename, string environmentFilename, 
											string sourceFilename, string targetFilename)
		{
			var parameters = new ParameterListBuilder().BuildParameterList(
				LoadXDocument(parameterFilename), 
				LoadXDocument(environmentFilename)
			);
			
			XDocument targetDoc = new ParameterisedXml(LoadXDocument(sourceFilename)).Transform(parameters);

			targetDoc.Save(targetFilename, SaveOptions.None);
		}

		private static XDocument LoadXDocument(string filename)
		{
			if (!File.Exists(filename))
			{
				throw new FileNotFoundException("Unable to find file '" + filename + "'");
			}

			return XDocument.Load(filename);
		}
	}
}
